package com.qiche.controller.mgr;

import com.github.pagehelper.PageInfo;
import com.qiche.aspect.Result;
import com.qiche.model.*;
import com.qiche.service.LuckyDrawService;
import com.qiche.service.PrizeItemService;
import com.qiche.service.ProductService;
import com.qiche.service.VoucherRepositoryService;
import com.qiche.util.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 抽奖管理
 * User: ZHS
 * Date: 2018/7/14 17:10
 */
@RestController
@RequestMapping("/luckydraw")
public class LuckyDrawController  {
    @Autowired
    private LuckyDrawService luckyDrawService;
    @Autowired
    private PrizeItemService prizeItemService;
    @Autowired
    private ProductService productService;
    @Autowired
    private VoucherRepositoryService repositoryService;

    @ApiOperation(value = "查询抽奖设置")
    @GetMapping
    public Map<String, Object> getAll() {
        Map<String, Object> map = new HashMap<>();
        LuckyDraw luckyDraw = null;
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        if (currentUser.getMerchantId() != 0 && currentUser.getMerchantId() != null) {
            luckyDraw = luckyDrawService.selectByMerchantId(currentUser.getMerchantId());
        }
        if (luckyDraw.getPercentage()!=null){
            luckyDraw.setPercentage(luckyDraw.getPercentage()*100);
        }
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("data", luckyDraw);
        return map;
    }

    @ApiOperation(value = "修改抽奖设置")
    @PostMapping("/addOrUpdate")
    public Result addOrUpdate(@RequestBody @Validated LuckyDraw luckyDraw) {
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        if (currentUser==null) {
            return Result.createByErrorMessage("登录失效!");
        }
        if (luckyDraw.getStartTime()!=null&&luckyDraw.getEndTime()!=null){
            long startTime = luckyDraw.getStartTime().getTime();
            long endTime = luckyDraw.getEndTime().getTime();
            if (endTime<startTime){
                return Result.createByErrorMessage("活动时间设置错误!");
            }
        }

        int count =0;
        LuckyDraw draw = luckyDrawService.selectByMerchantId(currentUser.getMerchantId());
        if (draw==null){
            if (luckyDraw.getLuckyDrawLimit()==null){
                luckyDraw.setLuckyDrawLimit(1);
            }else if (luckyDraw.getLuckyDrawLimit()==1){
                luckyDraw.setOverallLuckyDraw(0);
            }
            luckyDraw.setMerchantId(currentUser.getMerchantId());
            luckyDraw.setCreateTime(new Date());
            luckyDraw.setUpdateTime(new Date());
            count = luckyDrawService.insertResultId(luckyDraw);
        }else{
//            if (draw.getStartTime()!=null && draw.getEndTime()!=null){
//                Date date = new Date();
//                if (date.getTime()>draw.getStartTime().getTime()&&date.getTime()<draw.getEndTime().getTime()){
//                    return Result.createByErrorMessage("活动期间不准修改");
//                }
//            }
            if (luckyDraw.getLuckyDrawLimit()!=null && luckyDraw.getLuckyDrawLimit()==1){
                luckyDraw.setOverallLuckyDraw(0);
            }
            if (luckyDraw.getPercentage()!=null){
                luckyDraw.setPercentage(luckyDraw.getPercentage()/100);
            }
            luckyDraw.setId(draw.getId());
            luckyDraw.setUpdateTime(new Date());
            count = luckyDrawService.updateNotNull(luckyDraw);
        }

        if (count>0){
            return Result.createBySuccessMessage("保存成功");
        }
        return Result.createByErrorMessage("保存失败");
    }

    @ApiOperation(value = "查询抽奖奖项设置")
    @GetMapping("/prizeItemList")
    public Map<String, Object> prizeItemList() {
        List<PrizeItemVo> prizeItems = null;
        Map<String,Object> map  = new HashMap<>();
        LuckyDraw luckyDraw = null;
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        if (currentUser==null ) {
            map.put("code", 1);
            map.put("msg", "登录失效");
            return map;
        }
        luckyDraw = luckyDrawService.selectByMerchantId(currentUser.getMerchantId());
        if (luckyDraw==null){
            map.put("code", 1);
            map.put("msg", "未设置抽奖活动");
            return map;
        }
        prizeItems = prizeItemService.selectByLuckyDrawId(luckyDraw.getId());
        for (PrizeItemVo prizeItem :prizeItems){
            if (!prizeItem.getPrizeName().equals("未中奖")){
                if (prizeItem.getPrizeType()==1){
                    VoucherRepository repository =  repositoryService.selectByKey(prizeItem.getVoucherId());
                    prizeItem.setName(repository.getName());
                    prizeItem.setAmount(repository.getAmount());
                }else if (prizeItem.getPrizeType()==2){
                    Product product =  productService.selectById(prizeItem.getCardId());
                    prizeItem.setCategoryName(product.getName());
                    prizeItem.setProductName(product.getCategoryName());
                    prizeItem.setProductMoney(product.getPrice().toString());
                }else{
                }
            }

        }
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("data", prizeItems);
        map.put("count", prizeItems.size());
        return map;
    }
    @ApiOperation(value ="添加奖项" )
    @PostMapping("/add")
    public Result add(@RequestBody PrizeItem prizeItem) {
        User currentUser = UserUtils.getCurrentUser();
        if (currentUser.getMerchantId() == null) {
            return Result.createByErrorMessage("登录用户失效!");
        }
        if (prizeItem.getPrizeType()==1){
            VoucherRepository voucherRepository = repositoryService.selectByKey(prizeItem.getVoucherId());
            if (voucherRepository.getQuantity()<prizeItem.getPrizeCount()){
                return Result.createByErrorMessage("奖项卡卷数量过多");
            }
        }
        LuckyDraw luckyDraw = luckyDrawService.selectByMerchantId(currentUser.getMerchantId());
        if (luckyDraw==null){
            return Result.createByErrorMessage("还未添加抽奖活动");
        }
//        if (luckyDraw.getStartTime()!=null && luckyDraw.getEndTime()!=null){
//            Date date = new Date();
//            if (date.getTime()>luckyDraw.getStartTime().getTime()&&date.getTime()<luckyDraw.getEndTime().getTime()){
//                return Result.createByErrorMessage("活动期间不准修改");
//            }
//        }
        List<PrizeItemVo> prizeItems = prizeItemService.selectByLuckyDrawId(luckyDraw.getId());
        if (prizeItems.size()>8){
            return Result.createByErrorMessage("最多添加八种奖金项");
        }
        prizeItem.setLuckyDrawId(Long.parseLong(luckyDraw.getId().toString()));
        prizeItem.setCreateTime(new Date());
        prizeItem.setUpdateTime(new Date());
        boolean isOk = prizeItemService.insert(prizeItem)>0?true:false;
        if(isOk){
            return Result.createBySuccessMessage("添加成功");
        }
        return Result.createByErrorMessage("添加失败");
    }
    @ApiOperation(value = "根据ID删除奖项")
    @DeleteMapping(value = "/delete/{id}")
    public Result delete(@PathVariable("id") Long id) {
        User currentUser = UserUtils.getCurrentUser();
        if (currentUser.getMerchantId() == null) {
            return Result.createByErrorMessage("登录用户失效!");
        }
        LuckyDraw luckyDraw = luckyDrawService.selectByMerchantId(currentUser.getMerchantId());
//        if (luckyDraw.getStartTime()!=null && luckyDraw.getEndTime()!=null){
//            Date date = new Date();
//            if (date.getTime()>luckyDraw.getStartTime().getTime()&&date.getTime()<luckyDraw.getEndTime().getTime()){
//                return Result.createByErrorMessage("活动期间不准修改");
//            }
//        }
        int count = prizeItemService.deleteAddCount(id);
        if (count>0){
            return Result.createBySuccessMessage("删除成功");
        }else{
            return Result.createByErrorMessage("删除失败");
        }
    }
}
